/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ryan.ohos.extension.scroller.util;

public final class Pools {
    private Pools() {
    }

    public static class SynchronizedPool<T> extends SimplePool<T> {
        private final Object mLock = new Object();

        public SynchronizedPool(int maxPoolSize) {
            super(maxPoolSize);
        }

        public T acquire() {
            synchronized(this.mLock) {
                return super.acquire();
            }
        }

        public boolean release(T element) {
            synchronized(this.mLock) {
                return super.release(element);
            }
        }
    }

    public static class SimplePool<T> implements Pool<T> {
        private final Object[] mPool;
        private int mPoolSize;

        public SimplePool(int maxPoolSize) {
            if (maxPoolSize <= 0) {
                throw new IllegalArgumentException("The max pool size must be > 0");
            } else {
                this.mPool = new Object[maxPoolSize];
            }
        }

        public T acquire() {
            if (this.mPoolSize > 0) {
                int lastPooledIndex = this.mPoolSize - 1;
                T instance = (T) this.mPool[lastPooledIndex];
                this.mPool[lastPooledIndex] = null;
                --this.mPoolSize;
                return instance;
            } else {
                return null;
            }
        }

        public boolean release(T instance) {
            if (this.isInPool(instance)) {
                throw new IllegalStateException("Already in the pool!");
            } else if (this.mPoolSize < this.mPool.length) {
                this.mPool[this.mPoolSize] = instance;
                ++this.mPoolSize;
                return true;
            } else {
                return false;
            }
        }

        private boolean isInPool(T instance) {
            for(int i = 0; i < this.mPoolSize; ++i) {
                if (this.mPool[i] == instance) {
                    return true;
                }
            }

            return false;
        }
    }

    public interface Pool<T> {
        T acquire();

        boolean release(T var1);
    }
}
